import Mock from 'mockjs'
import { getRandomImage } from './common.js'

// 设置Mock请求的延迟时间
Mock.setup({
  timeout: '200-600'
})

// 生成模拟电视剧数据的函数
const generateDramas = (count, keyword = '') => {
  return Mock.mock({
    [`list|${count}`]: [
      {
        'id|+1': 1000,
        title: function () {
          // 确保标题包含关键词，提高相关性
          if (keyword) {
            return Mock.Random.ctitle(0, 2) + keyword + Mock.Random.ctitle(0, 3)
          }
          return Mock.Random.ctitle(3, 8)
        },
        description: function () {
          // 在描述中也可能包含关键词
          if (keyword) {
            return Mock.Random.cparagraph(1, 2) + keyword + Mock.Random.cparagraph(0, 1)
          }
          return Mock.Random.cparagraph(1, 3)
        },
        cover: () => getRandomImage(300, 400, 'drama'),
        'totalEpisodes|20-60': 1,
        'currentEpisode|1-50': 1,
        'rating|7.0-9.8': 1,
        'viewCount|10000-9999999': 1,
        'likeCount|1000-999999': 1,
        'tags|2-5': [
          '@pick(["动作", "冒险", "奇幻", "爱情", "悬疑", "科幻", "历史", "都市", "古装", "武侠", "家庭", "喜剧", "战争"])'
        ],
        'actors|2-4': [
          {
            name: '@cname',
            role: '@pick(["主演", "配角", "特邀出演"])'
          }
        ],
        director: '@cname',
        releaseDate: '@date("yyyy-MM-dd")',
        isNew: '@boolean',
        isCompleted: '@boolean',
        isPopular: '@boolean',
        // 搜索结果的相关性评分
        relevanceScore: '@integer(60, 100)'
      }
    ]
  }).list
}

/**
 * 搜索电视剧API
 * GET /api/search/dramas?keyword=xxx&pageSize=15&page=1
 */
Mock.mock(/\/api\/search\/dramas(\?.*)?$/, 'get', (options) => {
  const url = new URL('http://localhost' + options.url)
  const keyword = url.searchParams.get('keyword') || ''
  const page = parseInt(url.searchParams.get('page')) || 1
  const pageSize = parseInt(url.searchParams.get('pageSize')) || 15

  // 生成搜索结果
  const dramas = generateDramas(pageSize, keyword)

  // 模拟总记录数
  const total = keyword ? Mock.Random.integer(Math.max(pageSize, 30), 300) : 0
  const totalPages = Math.ceil(total / pageSize)

  return {
    code: 200,
    message: 'success',
    data: {
      keyword,
      list: dramas,
      pagination: {
        page,
        pageSize,
        total,
        totalPages,
        hasMore: page < totalPages
      },
      searchTime: Mock.Random.float(0.1, 2.0, 1, 2) // 搜索耗时(秒)
    }
  }
})

export default {
  generateDramas
}
